package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.domain.Dish;
import org.example.domain.DishFlavor;
import org.example.dto.Dishdto;
import org.example.mapper.DishMapper;
import org.example.service.DishFlavorService;
import org.example.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public void saveWithFlavor(Dishdto dishdto) {
        this.save(dishdto);
        List<DishFlavor> flavors = dishdto.getFlavors();
        Long id = dishdto.getId();
        for (DishFlavor dish :
                flavors) {
            dish.setDishId(id);
            dishFlavorService.save(dish);
        }
    }

    @Override
    public Dishdto getByIdWithFlavor(Long id) {
        Dish dish = this.getById(id);
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        Dishdto dishdto = new Dishdto();
        BeanUtils.copyProperties(dish, dishdto);
        dishdto.setFlavors(list);
        return dishdto;


    }

    @Override
    public void updataWithDishFlavor(Dishdto dishdto) {
        this.updateById(dishdto);
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishdto.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        List<DishFlavor> flavors = dishdto.getFlavors();
        for (DishFlavor dishFlavor :
                flavors) {
            dishFlavor.setDishId(dishdto.getId());
        }
        dishFlavorService.saveBatch(flavors);

    }
}
